<template>
  <el-dialog
    class="boundDialog"
    v-model="props.boundDialog"
    :title="props.boundForm?.boundTitle"
    width="35%"
    :show-close="false"
  >
    <el-row class="row">
      <el-col :span="8">
        <div>备件名称：{{ props.detailForm?.partName }}</div>
      </el-col>
      <el-col :span="8">
        <div>备件类型：{{ props.detailForm?.partTypeName }}</div>
      </el-col>
      <!-- <el-col :span="8">
        <div>当前可用库存：{{ props.detailForm?.availableStock }}</div>
      </el-col> -->
    </el-row>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      class="demo-ruleForsm"
      :size="formSize"
      status-icon
    >
      <el-form-item
        label="入库类型"
        prop="warehouseType"
        style="width: 90%"
        :rules="{
          required: true,
          message: '请选择入库类型',
          trigger: 'change'
        }"
      >
        <el-cascader
          v-model="ruleForm.warehouseType"
          ref="retrievalRef"
          :props="retrievalProps"
          :options="retrievalTypes"
          clearable
          placeholder="请选择入库类型"
          style="width: 100%"
          filterable
          :show-all-levels="false"
        />
      </el-form-item>
      <el-form-item
        label="入库批次"
        :prop="`detailRequests[0].batchNum`"
        :rules="{
          required: true,
          message: '请选择入库批次',
          trigger: 'change'
        }"
        style="width: 90%"
      >
        <el-select
          v-model="ruleForm.detailRequests[0].batchNum"
          style="width: 80%"
          class="m-2"
          placeholder="选择入库批次"
          @change="batchChange"
        >
          <el-option
            v-for="item in props.boundForm?.outBatch"
            :key="item.id"
            :label="item.batchNum"
            :value="item.batchNum"
          />
        </el-select>
        <el-button type="primary" @click="addBatch" style="width: 20%"
          >新增批次</el-button
        >
      </el-form-item>
      <el-form-item label="备件单价" style="width: 90%">
        <el-input
          v-model="price"
          autocomplete="off"
          placeholder=""
          disabled
          style="width: 95%"
        />元
      </el-form-item>
      <el-form-item
        label="入库数量"
        style="width: 90%"
        :prop="`detailRequests[0].amount`"
        :rules="{
          required: true,
          message: '请选择入库数量',
          trigger: 'blur'
        }"
      >
        <el-input
          v-model="ruleForm.detailRequests[0].amount"
          autocomplete="off"
          type="text"
          maxlength="8"
          onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^123456789]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
          onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-19]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
          placeholder="请输入入库数量"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="cancel(ruleFormRef)"> 取消 </el-button>
        <el-button
          type="primary"
          @click="submit(ruleFormRef)"
          :loading="loading"
          >确认</el-button
        >
      </el-form-item>
    </el-form>
    <AddBatch
      :batchDialog="batchDialog"
      :partId="props.detailForm?.id"
      @cancelBatch="cancelBatch"
      @submitBatch="submitBatch"
    ></AddBatch>
  </el-dialog>
</template>
<script setup lang="ts">
import { ElMessage, ElTree, FormInstance, FormRules } from 'element-plus'
import { ref, reactive, watch, defineAsyncComponent } from 'vue'
import { dictionaryList } from '/@/api/publicApi/index'
import { getBatchApi, savePartWarehouseApi } from '/@/api/spare/index'
const AddBatch = defineAsyncComponent(() => import('./AddBatch.vue'))
const props = defineProps({
  boundDialog: Boolean,
  boundForm: Object,
  detailForm: Object
})
const emit = defineEmits(['cancelIn', 'refreshBatch', 'submitIn'])
const formSize = ref('default')
const loading = ref(false)
const batchDialog = ref(false)
const ruleFormRef = ref<FormInstance>()
const retrievalTypes = ref<any>([])
const price = ref('')
const retrievalProps = {
  expandTrigger: 'click' as const,
  value: 'configValue',
  label: 'configValue',
  emitPath: false
}
const ruleForm = ref({
  warehouseType: '',
  detailRequests: [
    {
      partId: '',
      batchNum: '',
      amount: ''
    }
  ]
})
const rules = reactive<FormRules>({
  retrievalType: [
    { required: true, message: '请选择入库类型', trigger: 'change' }
  ]
})

const getOutType = () => {
  dictionaryList({ configType: 'warehouse_type', keyword: '' }).then((res) => {
    if (res.code == 0) {
      retrievalTypes.value = res.data
      retrievalTypes.value.forEach((i: any) => {
        if (i.configValue == '库存新增') {
          ruleForm.value.warehouseType = i.configValue
        }
      })
    }
  })
}
getOutType()

const addBatch = () => {
  batchDialog.value = !batchDialog.value
}

const cancelBatch = () => {
  emit('refreshBatch', props.detailForm?.id)
  batchDialog.value = !batchDialog.value
}

const submitBatch = (val: any) => {
  emit('refreshBatch', props.detailForm?.id)
  getBatchApi(props.detailForm?.id, '2').then((res) => {
    if (res.code == 0) {
      res.data.forEach((i: any) => {
        if (i.batchNum == val) {
          ruleForm.value.detailRequests[0].batchNum = i.batchNum
          price.value = i.price
        }
      })
    }
  })
  batchDialog.value = !batchDialog.value
}

const batchChange = (val: any) => {
  if (val == '') {
    price.value = ''
  } else {
    props.boundForm?.outBatch.forEach((i: any) => {
      if (i.batchNum == val) {
        price.value = i.price
      }
    })
  }
}

const cancel = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  price.value = ''
  emit('cancelIn')
}
const submit = (formEl: FormInstance | undefined) => {
  loading.value = true
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      ruleForm.value.detailRequests[0].partId = props.detailForm?.id
      savePartWarehouseApi(ruleForm.value).then((res) => {
        if (res.code == 0) {
          ElMessage({
            type: 'success',
            message: '入库成功'
          })
          price.value = ''
          emit('submitIn')
        }
      })
      loading.value = false
    } else {
      loading.value = false
    }
  })
}
</script>
<style scoped lang="scss">
.boundDialog {
  .row {
    font-size: var(--el-font-size-base);
    margin-bottom: 8px;

    > div {
      text-align: center;
    }
  }
}
</style>
